﻿using HandyControl.Data;
using MailKit;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using RecordBill.Core;
using RecordBill.Data;
using RecordBill.Dtos;
using RecordBill.Extensions;
using RecordBill.Views;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Documents;

namespace RecordBill.ViewModels
{
    internal class BillStatisticsViewModel : BindableBase, INavigationAware
    {
        private readonly ImportService _impServer;
        private readonly QQMailService _mailServer;


        private int _selectedType;
        /// <summary>
        /// 1:微信账单，2：支付宝账单
        /// </summary>
        public int SelectedType
        {
            get => _selectedType; set
            {
                _selectedType = value;
                RaisePropertyChanged();
            }
        }

        private List<UIComboxItem> _billTypeCombox;

        public List<UIComboxItem> BillTypeCombox
        {
            get
            {
                return _billTypeCombox;
            }
            set
            {
                _billTypeCombox = value;
                RaisePropertyChanged();
            }
        }

        private ObservableCollection<Transaction> _listBillItems;

        public ObservableCollection<Transaction> ListBillItems
        {
            get => _listBillItems;
            set
            {
                _listBillItems = value;
                RaisePropertyChanged();
            }
        }

        private UIBillStatisticsInfo _billInfo;
        public UIBillStatisticsInfo BillInfo
        {
            get => _billInfo; set
            {
                _billInfo = value;
                RaisePropertyChanged();
            }
        }
        private readonly IDialogService _dialogSer;

        private PageQueryBill _billQuery;
        public PageQueryBill BillQuery
        {
            get => _billQuery;
            set
            {
                _billQuery = value;
                RaisePropertyChanged();
            }
        }

        private UIBillStatisticsInfo _pageBillInfo;
        public UIBillStatisticsInfo PageBillInfo
        {
            get => _pageBillInfo; set
            {
                _pageBillInfo = value;
                RaisePropertyChanged();
            }
        }

        public DelegateCommand<FunctionEventArgs<int>> BillPageUpdatedCommand { get; set; }
        public DelegateCommand EmialAsyncBillCommand { get; set; }
        public DelegateCommand OtherAsyncBillCommand { get; set; }
        public DelegateCommand SaveDbCommand { get; set; }
        public DelegateCommand QueryBillCommand { get; set; }
        

        public BillStatisticsViewModel(IDialogService dialogSer, ImportService impService, QQMailService mailService)
        {
            Init();

            var currentDate = DateTime.Now;
            // 获取当前日期的年份和月份
            int currentYear = currentDate.Year;
            int currentMonth = currentDate.Month;
            var preMonth = new DateTime(currentYear, currentMonth, 1).AddMonths(-1);
            // 计算上个月的最后一天
            DateTime lastDayOfPreviousMonth = preMonth.AddMonths(1).AddDays(-1);

            BillQuery = new PageQueryBill()
            {
                PageSize = 15
            };
            BillQuery.StartTime = preMonth;
            BillQuery.EndTime = lastDayOfPreviousMonth;
            ListBillItems = new ObservableCollection<Transaction>();
            _impServer = impService;
            _mailServer = mailService;
            _dialogSer = dialogSer;
            EmialAsyncBillCommand = new DelegateCommand(ImportBillData);
            OtherAsyncBillCommand = new DelegateCommand(OpenOtherClassify);
            SaveDbCommand = new DelegateCommand(SaveDb);
            BillPageUpdatedCommand = new DelegateCommand<FunctionEventArgs<int>>(BillPageQuery);
            QueryBillCommand = new DelegateCommand(QueryBill);
            LoadBills();
        }

       
        private void Init()
        {
            var list = new List<UIComboxItem>();
            list.Add(new UIComboxItem()
            {
                Value = 1,
                Text = "微信账单"
            });
            list.Add(new UIComboxItem()
            {
                Value = 2,
                Text = "支付宝账单"
            });
            BillTypeCombox = list;
            SelectedType = 1;
        }
        private void BillPageQuery(FunctionEventArgs<int> info)
        {
            BillQuery.PageIndex = info.Info;
            LoadBills();
        }

        private void QueryBill()
        {
            BillQuery.PageIndex = 0;
            BillQuery.PageCount = 0;
            LoadBills();
        }

        private void LoadBills()
        {
            var pageResult = _impServer.QueryBillItems(BillQuery);
            if (pageResult == null) return;
            PageBillInfo = pageResult.Data;
            BillQuery.PageCount = (int)Math.Ceiling(pageResult.TotalCount * 1.0 / BillQuery.PageSize);
        }

        private async void ImportBillData()
        {
           
            var listExcelZip = await DownloadEmailBill();
            List<Transaction> listBillItems = new List<Transaction>();
            List<string> listExcels = new List<string>();
            if (listExcelZip?.Count > 0)
            {
                foreach (var excelPath in listExcelZip)
                {
                    var name = Path.GetFileName(excelPath);
                    string result = Microsoft.VisualBasic.Interaction.InputBox("请输入" + name + "的解压密码", "输入框", "", -1, -1);
                    if (!string.IsNullOrEmpty(result))
                    {
                        // 处理输入结果
                        var tempList = DecompressHelper.ExtractFiles(excelPath, result);
                        listExcels.AddRange(tempList);
                    }
                }

                if (listExcels?.Count > 0)
                {
                    foreach (var excel in listExcels)
                    {
                        if(SelectedType==1)
                        {
                            BillInfo = DataImport.ImportFile(excel);
                            var data = BillInfo.BillItemList;
                            if (data?.Count > 0)
                            {
                                listBillItems.AddRange(data);
                            }
                        }
                        else
                        {
                            var list= DataImport.ParseCashbookRecordsSkipHeader(excel);

                            if(list?.Count>0)
                            {
                                foreach (var item in list)
                                {
                                    var trans = new Transaction();
                                    trans.Amount = item.金额;
                                    trans.Counterparty = item.备注;
                                    trans.Goods = item.备注;
                                    trans.IncomeOrExpense = item.收支类型;
                                    trans.TradeTime = item.记录时间;
                                    trans.PaymentMethod = item.账户;
                                    trans.TradeType = item.标签;
                                    trans.StatisticsType = item.分类;
                                    trans.TransactionId = Guid.NewGuid().ToString();
                                    trans.MerchantOrderId = "";
                                    trans.Status = "成功";
                                    listBillItems.Add(trans);
                                }
                               
                            }

                        }
                       
                    }
                }
            }

            if (listBillItems.Count > 0)
            {
                ListBillItems.AddRange(listBillItems);
                OpenOtherClassify();
            }
        }

        private void OpenOtherClassify()
        {
            if((ListBillItems?.Count > 0)==false)
            {
                return;
            }
            var listOthers = ListBillItems.Where(a => a.StatisticsType == "其他").ToList();

            if(listOthers?.Count>0==false)
            {
                return;
            }
            foreach (var other in listOthers)
            {
                ListBillItems.Remove(other);
            }  
            listOthers = listOthers.OrderBy(a => a.StatisticsType).ToList();
            var par = new DialogParameters();
            par.Add(PrismManager.OtherKey, listOthers);
            _dialogSer.ShowDialog(nameof(BillOtherClassifyView), par, callback =>
            {
                ListBillItems.AddRange(listOthers);
            });
        }

        private async void SaveDb()
        {
            if (ListBillItems?.Count > 0)
            {
                await _impServer.SaveToDatabaseAsync(ListBillItems.ToList());
            }
        }

        private async Task<List<string>> DownloadEmailBill()
        {
            var mailService = _mailServer;

            // 替换为你的QQ邮箱和授权码
            string email = ConfigSettings.Email;
            string password = ConfigSettings.EmailKey; // 注意：这里是授权码，不是QQ密码
            string dir = ConfigSettings.DownloadDir;
            var emails=new List<EmailMessage>();
            if(SelectedType==1)
            {
                emails = await mailService.ReadEmailsWithDownloadLinksAsync(
              email, password, maxEmails: 10);
            }
            else
            {
                emails = await mailService.ReadEmailsWithDownloadLinksAsync(
              email, password, 2,maxEmails: 10);
            }
           
            List<string> list = new List<string>();
            if (emails.Count > 0)
            {
                Console.WriteLine($"找到 {emails.Count} 封包含下载链接的邮件:\n");

                foreach (var emailMsg in emails)
                {
                    emailMsg.PrintInfo();
                    if(SelectedType==1)
                    {
                        if (emailMsg.DownloadLinks.Count > 0)
                        {

                            var link = emailMsg.DownloadLinks.FirstOrDefault(a => a.Contains("userbilldownload"));
                            if (!string.IsNullOrWhiteSpace(link))
                            {
                                var savePath = dir + emailMsg.Subject + DateTime.Now.ToString("yyyyMMddmmssff") + ".zip";
                                await FileDownloader.DownloadExcelFileAsync(link, savePath);
                                list.Add(savePath);
                            }
                        }
                    }
                    else
                    {
                        list.AddRange(emailMsg.DownloadLinks);
                    }
                    
                }
                return list;
            }
            else
            {
                return null;
            }

        }

        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return true;
        }

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {

        }

        public void OnNavigatedTo(NavigationContext navigationContext)
        {

        }

    }
}
